import Dialog from "@vant/weapp/dialog/dialog";

const app = getApp();
const {
    AskPage
} = app._require('common/index');
const formMixin = app._require("mixins/form.mixin.js").default;
import {handleMixin} from "./action";

AskPage({
    name: "collection-details",
    mixins: [formMixin, handleMixin],
    data: {
        activeNames: [],
        validate: [],
        type: '',
        processInstanceId: '',
        category: '',
        approvalStatus: '',
        userId: '',
        minData: new Date(1890, 0, 1).getTime(),
        maxData: new Date(2071, 1, 1).getTime(),
        activeIdSelect: '',
        currentItemSelect: null,
        model: {
            dataCount: 0,
            state: 2,
            executor: "",
            formId: "",
            shareId: "",
            makePhone: "",
            id: "",
            taskId: "",
            name: "",
            readonly: true,
            line: 0,
            description: "",
        },
        // 表单项列表
        formItemList: [],
        dataId: '',
        field: '',
        parentId: '',
        typeId: '',
        onlyWord: '',
        onlyIdList: []
    },

    onShow() {
        wx.hideHomeButton();
        //检测更新
        app.checkProkectSystem();
    },
    onLoad(options) {
        this.setData({
            dataId: options.id,
            field: options.currentFiled,
            parentId: options.currentId,
            typeId: options.currentId
        });
        this.getOnlyWord();
    },
    async getOnlyWord() {
        const response = await this.$_server("searchData/getOnly", {
            params: {
                typeId: `?typeId=${this.data.typeId}`
            },
        });
        let {data} = response;
        if (data.code !== 200) {
            this.setData({
                onlyWord: ''
            });
            this.initForm();
            throw data;
        }
        const list = data.data.map((item) => item.map((it) => it.labelName));
        let onlyIdList = [];
        if (this.data.dataId) {
            data.data.forEach((item) => {
                item.forEach((it) => {
                    onlyIdList.push(it.labelId);
                });
            });
        }
        this.setData({
            onlyWord: list.map((item, index) => (index + 1) + "." + item.join("+")).join(" "),
            onlyIdList: onlyIdList
        });
        this.initForm();
    },
    async initForm() {
        let model = {};
         if(this.data.dataId) {
            model = await this.initDetailsData();
        }
        this.initDetails(model);
    },
    // 获取填报数据
    async initDetailsData() {
        try {

            let request_url = "form/reportDetail";
            if(this.data.type == 'sb_report'){
                //上报
                request_url = 'form/sbReportDetail'
            }

           const response = await this.$_server("searchData/getInfo", {
                data: {
                    dataId: this.data.dataId,
                    field: this.data.field,
                    parentId: this.data.parentId,
                    typeId: this.data.typeId
                },
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }
            let resourceUrl = this.data.$_config.url;
            const formData = data.data;
            formData.forEach(item => {
                item.dataList.forEach(it => {
                    let valueData = it.valueData
                    if (it.valueKindId === "7") {
                        valueData = it.valueData.split(",")
                    } else if (it.valueKindId === "9") {
                        valueData = it.valueData && it.valueData.length ? it.valueData.map(src => {
                            return cur.includes(resourceUrl) ? cur : resourceUrl + (src.indexOf("\/") === 0 ? src : "/" + src)
                        }) : []
                    } else if (it.valueKindId === "4") {
                        valueData = valueData ? {
                            cityCode: null,
                            cityInfo: valueData.cityInfo,
                            info: valueData.cityAddress,
                            longitude: valueData.longitude,
                            latitude: valueData.latitude
                        } : {}
                    } else if (["5", "8", "10"].includes(it.valueKindId)) {
                        valueData = valueData ? valueData.map(cur => {
                            return {
                                src: cur.includes(resourceUrl) ? cur : resourceUrl + (cur.indexOf("\/") === 0 ? cur : "/" + cur),
                                fileName: this.getName(cur)
                            }
                        }) : [];
                    } else if (["3", "11"].includes(it.valueKindId)) {
                        valueData = it.valueData ? it.valueData.replace(/-/g, "/") : '';
                    }
                    this.setData({
                        ["model." + item.field + it.en]: valueData
                    });
                })
            })
            return formData;
        } catch (error) {
            console.log(error);
            // statements
            if (error.message) {
                wx.showToast({
                    mask: true,
                    title: error.message,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    // 获取表单模板
    async initDetails() {
        try {
            const response = await this.$_server("searchData/getForm", {
                data: {
                    secondTypeId: this.data.typeId
                },
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }

            const formList = [];
            const activeNames = this.data.activeNames;

            data.data.forEach((item) => {
                const obj = {
                    itemType: 0,
                    items: [],
                    name: item.typeName,
                    typeId: item.typeId,
                    typeField: item.typeField
                };
                activeNames.push(item.typeId);
                item.labelList.forEach((it) => {
                    obj.items.push({
                        name: it.name,
                        itemType: 2,
                        field: it.field,
                        id: item.typeField + it.field, // 适应组件回显逻辑用的id
                        valueKindId: it.valueKindId,
                        unitKindId: it.unitKindId,
                        unitKindName: it.unitKindName,
                        options: it.optionList ? it.optionList.map(op => { return { id: op, label: op, value: op } }) : [],
                        resId: it.id, // 原数据id
                        disabled: this.data.onlyIdList.includes(it.id)
                    });
                });
                formList.push(obj);
            });

            this.setData({
                activeNames: activeNames,
                formItemList: formList || []
            });
        } catch (error) {
            let errorTitle = error.message || "操作失败";
            this.setData({
                "loadError": false,
                "errorTitle": errorTitle
            })
        }
    },
    // 获取文件名称
    getName(val) {
        if (!val.includes("?")) return val;
        const params = val.split("?")[1].split("&");
        const obj = {};
        params.forEach((item) => {
            obj[item.split("=")[0]] = item.split("=")[1];
        });
        return obj.name;
    },
    //单选
    onSelectClick(e) {
        let {key, keyid, value} = e.currentTarget.dataset;
        let {value: item} = e.detail;

        if (Array.isArray(key)) {
            // 在表格中
            let str = "model.";
            key.forEach(item => {
                if (typeof item === "number") {
                    str += "[" + item + "]";
                } else {
                    str += item;
                }
            });

            // 判断新值旧值是否相等，相等的话就是取消选中
            let _value = value || "";
            if (_value === item.value) {
                _value = "";
            } else {
                _value = item.value;
            }

            const opt = {};
            opt[str] = _value;
            this.setData(opt);
        } else {
            // 判断新值旧值是否相等，相等的话就是取消选中
            let _value = this.data.model[key] || "";
            if (_value === item.value) {
                _value = "";
            } else {
                _value = item.value;
            }

            // 赋值
            this.setData({
                ["model." + key]: _value,
            });
        }
    },
    //多选
    onCascaderClick(e) {
        let {key} = e.currentTarget.dataset;
        let { value: item } = e.detail;
        let _key = "model." + key;
        if (Array.isArray(key)) {
            // 在表格中
            _key = "model.";
            key.forEach(it => {
                if (typeof it === "number") {
                    _key += "[" + it + "]";
                } else {
                    _key += it;
                }
            });
        }
        this.setData({
            [_key]: item,
        });
    },

    locationChange(e) {
        // 真实key，可能是表格中，就是数组
        const {key: sKey} = e.currentTarget.dataset;
        // 控件选的是定位还是输入详细地址
        const {key} = e.detail.currentTarget.dataset;
        const {value} = e.detail.detail;
        let _key = "";
        if (key === "address") {
            _key = sKey;
        } else {
            if (Array.isArray(sKey)) {
                _key = [].concat([], sKey);
                _key.push("info");
            } else {
                _key = key.replace("address", sKey);
            }
        }
        this.setModel({
            currentTarget: {
                dataset: {
                    key: _key
                }
            },
            detail: {
                value
            },
        });
    },
    onTextAreaChange(e) {
        const {key: sKey} = e.currentTarget.dataset;
        const value = e.detail;

        this.setModel({
            currentTarget: {
                dataset: {
                    key: sKey,
                },
            },
            detail: {
                value: value,
            },
        });
    },
    async sure() {
        if (!this.data.activeIdSelect) {
            wx.askShowToastEx({
                mask: true,
                title: '请选择镇上审核人',
                icon: "none",
                duration: 2000,
            });
            return false
        }
        const itemValueList = []
        this.data.formItemList.forEach((item) => {
            item.items.forEach((it) => {
                let sourceData = this.data.model[item.typeField + it.field]
                if (["5", "8", "10"].includes(it.valueKindId)) {
                    sourceData = sourceData ? sourceData.map(cur => {
                        if (cur.src.includes(this.data.$_config.url.length)) {
                            return cur.src.substring(this.data.$_config.url.length);
                        } else {
                            return cur.src;
                        }
                    }) : null
                    itemValueList.push({
                        extData: sourceData,
                        itemValue: null,
                        labelId: it.resId
                    });
                } else if (it.valueKindId === '9') {
                    if (typeof sourceData === "string") {
                        sourceData = sourceData ? [sourceData.substring(this.data.$_config.url.length)] : null;
                    } else {
                        sourceData = null;
                    }
                    itemValueList.push({
                        extData: sourceData,
                        itemValue: null,
                        labelId: it.resId
                    });
                } else if (it.valueKindId === '4') {
                    sourceData = sourceData ? {
                        cityAddress: sourceData.info,
                        cityName: sourceData.cityInfo,
                        latitude: sourceData.latitude,
                        longitude: sourceData.longitude
                    } : null;
                    itemValueList.push({
                        extData: sourceData,
                        itemValue: null,
                        labelId: it.resId
                    });
                } else if (it.valueKindId === '7') {
                    sourceData = sourceData ? sourceData.join(",") : "";
                    itemValueList.push({
                        extData: null,
                        itemValue: sourceData,
                        labelId: it.resId
                    });
                } else if (it.valueKindId === '3') {
                    sourceData = (sourceData || sourceData === 0) ? new Date(sourceData).format("yyyy/MM/dd") : "";
                    itemValueList.push({
                        extData: null,
                        itemValue: sourceData,
                        labelId: it.resId
                    });
                } else if (it.valueKindId === '11') {
                    sourceData = (sourceData || sourceData === 0) ? new Date(sourceData).format("yyyy/MM/dd hh:mm:ss") : "";
                    itemValueList.push({
                        extData: null,
                        itemValue: sourceData,
                        labelId: it.resId
                    });
                } else {
                    itemValueList.push({
                        extData: null,
                        itemValue: sourceData || '',
                        labelId: it.resId
                    });
                }
            });
        });
        try {
            const response = await this.$_server("searchData/save", {
                data: {
                    itemValueList,
                    secondTypeId: this.data.typeId,
                    approveUserId: this.data.activeIdSelect
                },
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }
            wx.askShowToastEx({
                mask: true,
                title: "本次修改将于5分钟后生效，请届时查看！",
                duration: 2000,
                icon: "none"
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 500)
        } catch (error) {
            if (error.message) {
                wx.askShowToastEx({
                    mask: true,
                    title: error.message,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    selectPeople() {
        wx.navigateTo({
            url: `/pages/resource-search/select/index?id=${this.data.activeIdSelect}`
        })
    },
    clearPageData() {
        const data = {
            model: {
                dataCount: 0,
                state: 2,
                executor: "",
                formId: "",
                shareId: "",
                makePhone: "",
                id: "",
                taskId: "",
                name: "",
                readonly: true,
                line: 0,
                description: "",
            },
            // 表单项列表
            formItemList: []
        };
        this.setData(data);
    },
    confirm() {
        const beforeClose = action =>
            new Promise(resolve => {
                setTimeout(() => {
                    if (action === "confirm") {
                        this.setData({
                            "clickNext": true
                        })
                        this.clearPageData();
                        setTimeout(() => {
                            this.onLoad(this.data.onLoadOption);
                            resolve(true);
                        });
                    } else {
                        this.goBack();
                        resolve(true);
                    }
                }, 100);
            });

        Dialog.confirm({
            title: "提示",
            message: "是否继续填写下一条？",
            beforeClose,
            cancelButtonText: "完成",
            confirmButtonText: "下一条"
        });
    },
    // 删除行
    deleteRow(e) {
        wx.showModal({
            title: "",
            content: "是否确认删除?",
            success: (res) => {
                if (res.confirm) {
                    const {tableItem, index} = e.currentTarget.dataset;
                    const list = this.data.formItemList;
                    const delRow = (arr) => {
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].itemType === 0) {
                                delRow(arr[i].items);
                            } else if (arr[i].itemType === 1 && tableItem.id === arr[i].id) {
                                arr[i].rows.splice(index, 1);
                                break;
                            }
                        }
                    };
                    delRow(list);
                    this.setData({
                        formItemList: list
                    });

                    const data = this.data.model[tableItem.childrenFormId];
                    if (data) {
                        data.splice(index, 1);
                        this.setData({
                            ["model." + tableItem.childrenFormId]: data
                        });
                    }
                }
            }
        })
    },
    // 添加行
    addRow(e) {
        const {tableItem, index} = e.currentTarget.dataset;
        const list = this.data.formItemList;
        const addR = (arr) => {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].itemType === 0) {
                    addR(arr[i].items);
                } else if (arr[i].itemType === 1 && tableItem.id === arr[i].id) {
                    arr[i].rows.splice(index + 1, 0, {
                        ...arr[i].rows[0],
                        id: this.getRandomId()
                    });
                    break;
                }
            }
        };
        addR(list);

        this.setData({
            formItemList: list
        });
        wx.showToast({
            title: '添加成功',
            icon: "none"
        })
    },
    goBack(callback) {
        wx.navigateBack({
            complete: () => {
                callback && callback();
            },
        });
    },
    onChange(event) {
        if (this.data.isClickAction == true) {
            return
        }
        var that = this;
        this.setData({
            isClickAction: true
        })
        setTimeout(function () {
            that.setData({
                activeNames: event.detail,
                isClickAction: false
            });
        }, 300)

    },
    setValueModel: function(e){
        console.log(e);
        const {key,valuekindid} = e.currentTarget.dataset;
        var value = e.detail.value;

        //判断pc上输入数字异常
        if(valuekindid == '12'  && !this.chk(value) ){
            value=value.slice(0, -1)
        }

        if (valuekindid == '13' && !this.chkd(value)) {
            value = value.slice(0, -1)
        } else {
            if (value.split('.')[1] && value.split('.')[1].length > 2) {
                value = value.slice(0, -1)
            }
        }

        this.setData({
            ["model." + key]: value
        })
    },
    setPeople(item) {
        console.log(item);
        debugger
        this.setData({
            activeIdSelect: item.activeIdSelect,
            currentItemSelect: item.currentItemSelect
        })
    }
});
